package com.platform.service.impl;

import com.platform.annotation.SysLog;
import com.platform.base.BaseService;
import com.platform.common.Const;
import com.platform.common.ServerResponse;
import com.platform.dao.AttachmentMapper;
import com.platform.pojo.Attachment;
import com.platform.service.IAttachmentService;
import com.platform.service.IFileService;
import com.platform.util.NumberUtil;
import com.platform.util.PropertiesUtil;
import com.platform.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * 附件服务层
 */
@Service("iAttachmentService")
public class AttachmentServiceImpl extends BaseService implements IAttachmentService {

    private static String hdfile = PropertiesUtil.getProperty("hdfile");


    @Autowired
    private IFileService iFileService;
    /**
     * 根据条件查询附件
     * @param entityName 实体名称
     * @param entityType 实体类型
     * @param entityId 实体ID
     * @return
     */
    @SysLog("查询附件信息")
    public ServerResponse<List<Attachment>> findByParam(String entityName,String entityType,Integer entityId){
        List<Attachment> resultList = attachmentMapper.selectByParam(entityName,entityType,entityId);
        if(null != resultList && 0 < resultList.size()){
            return ServerResponse.createBySuccess(Const.Msg.SELECTSUCCESS,resultList);
        }
        return ServerResponse.createByErrorMessage(Const.Msg.SELECTERROR);
    }


    /**
     * 保存多附件
     * @param fileList 附件集合
     * @param setPageName 保存文件夹名称
     * @param path 文件存储文件夹
     * @param entityName 实体名称
     * @param entityType 实体附件类型
     * @param entityId 实体ID
     * @return
     */

    @SysLog("新增附件（集合）")
    public String saveFileList(List<MultipartFile> fileList, String setPageName,
                               String path, String entityName,
                               String entityType, Integer entityId, HttpServletRequest request) {
        Integer resultNum = 0;
        if(null != fileList && 0 < fileList.size()){
            for (int i = 0; i < fileList.size(); i++) {
                if(fileList.get(i).getSize() <= 0){
                    continue;
                }
                String targetFileName = iFileService.upload(fileList.get(i),path,setPageName);//返回文件名 上传失败返回null
                if(StringUtil.isNotEmpty(targetFileName)){
                    //附件成功保存至FTP服务器后则保存附件信息
                    Attachment attachment = new Attachment();
                    attachment.setEntityname(entityName);//实体名称
                    attachment.setEntitytype(entityType);//附件类型
                    attachment.setEntityid(entityId);//实体ID
                    attachment.setFilename(fileList.get(i).getOriginalFilename());//原始文件名
                    attachment.setFiledownpath(setPageName+ File.separator+targetFileName);//下载路径
                    attachment.setFilesize(fileList.get(i).getSize()+"");//文件大小
                    attachment.setFilepath(hdfile+setPageName+ File.separator+targetFileName);//磁盘路径
                    resultNum+=attachmentMapper.insert(attachment);
                }
            }
        }
        return resultNum.toString();
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @SysLog("删除附件")
    public ServerResponse<String> del(Integer id){
        if(attachmentMapper.deleteByPrimaryKey(id)>0){
            return ServerResponse.createBySuccessMessage(Const.Msg.DELSUCCESS);
        }
        return ServerResponse.createByErrorMessage(Const.Msg.DELERROR);
    }


    /**
     * 保存单个附件
     * @param file 文件类
     * @param setPageName 保存文件夹
     * @param path 保存路径
     * @param entityName 实体名称
     * @param entityType 实体附件类型
     * @param entityId 实体ID
     * @return
     */
    @SysLog("新增附件（单个）")
    public ServerResponse<String> insertAttachment(MultipartFile file, String setPageName,
                                                   String path, String entityName,
                                                   String entityType, Integer entityId){
        if(file != null && file.getSize() > 0){
            String targetFileName = iFileService.upload(file,path,setPageName);//返回文件名 上传失败返回null
            if(StringUtil.isNotEmpty(targetFileName)){
                //附件成功保存至FTP服务器后则保存附件信息
                Attachment attachment = new Attachment();
                attachment.setEntityname(entityName);//实体名称
                attachment.setEntitytype(entityType);//附件类型
                attachment.setEntityid(entityId);//实体ID
                attachment.setFilename(file.getOriginalFilename());//原始文件名
                attachment.setFiledownpath(setPageName+ File.separator+targetFileName);//下载路径
                attachment.setFilesize(file.getSize()+"");//文件大小
                attachment.setFilepath(hdfile+setPageName+ File.separator+targetFileName);//磁盘路径
                if(attachmentMapper.insert(attachment) > 0){
                    return ServerResponse.createBySuccessMessage(Const.Msg.SAVESUCCESS);
                }
            }

        }
        return ServerResponse.createByErrorMessage("没有上传附件");
    }


    /**
     * 保存单个附件，主要用于导入上传附件
     * @param file
     * @return
     */
    @SysLog("导入上传附件")
    public ServerResponse<Attachment> saveFile(String pageName,MultipartFile file,HttpServletRequest request){
        if(file != null && file.getSize() > 0){
            String path =  request.getSession().getServletContext().getRealPath("/upload");//文件存储文件夹
            String targetFileName = iFileService.upload(file,path,pageName);//返回文件名 上传失败返回null
            if(StringUtil.isNotEmpty(targetFileName)){
                //附件成功保存至FTP服务器后则保存附件信息
                Attachment attachment = new Attachment();
                attachment.setEntityname(PropertiesUtil.getProperty("importEntityName"));//实体名称
                attachment.setEntitytype(PropertiesUtil.getProperty("importEntityType"));//附件类型
                attachment.setEntityid(0);//实体ID
                attachment.setFilename(file.getOriginalFilename());//原始文件名
                attachment.setFiledownpath(pageName+ File.separator+targetFileName);//下载路径
                attachment.setFilesize(file.getSize()+"");//文件大小
                attachment.setFilepath(hdfile+pageName+ File.separator+targetFileName);//磁盘路径
                if(attachmentMapper.insert(attachment) > 0){
                    return ServerResponse.createBySuccess(Const.Msg.SAVESUCCESS,attachment);
                }
            }
        }
        return ServerResponse.createByErrorMessage("没有上传附件");
    }

    /**
     * 上传图片
     * @param pageName
     * @param file
     * @param request
     * @return
     */
    @SysLog("上传图片")
    public ServerResponse<Attachment> uploadImage(String pageName,String entityName,String entityType,
                                                  String id,MultipartFile file,HttpServletRequest request){
        if(file != null && file.getSize() > 0){
            Integer eid = NumberUtil.safeToNumber(id);
            if(eid <= 0){
                return ServerResponse.createByErrorMessage(Const.Msg.PARAMTERERROR);
            }
            String path =  request.getSession().getServletContext().getRealPath("/upload");//文件存储文件夹
            String targetFileName = iFileService.upload(file,path,pageName);//返回文件名 上传失败返回null
            if(StringUtil.isNotEmpty(targetFileName)){
                //附件成功保存至FTP服务器后则保存附件信息
                Attachment attachment = new Attachment();
                attachment.setEntityname(entityName);//实体名称
                attachment.setEntitytype(entityType);//附件类型
                attachment.setEntityid(eid);//实体ID
                attachment.setFilename(file.getOriginalFilename());//原始文件名
                attachment.setFiledownpath(pageName+ File.separator+targetFileName);//下载路径
                attachment.setFilesize(file.getSize()+"");//文件大小
                attachment.setFilepath(hdfile+pageName+ File.separator+targetFileName);//磁盘路径
                if(attachmentMapper.insert(attachment) > 0){
                    return ServerResponse.createBySuccess(Const.Msg.SAVESUCCESS,attachment);
                }
            }
        }
        return ServerResponse.createByErrorMessage("没有上传附件");
    }

}
